<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>TICK</title>
    <!-- 按需替换路径 -->
    <script type="text/javascript" src="http://127.0.0.1:8090/libac"></script>
    <style type="text/css"></style>
  </head>

  <body></body>
</html>

<script>
  let i = 0
  let urlParam = window.location.search.slice(1)
  let urlParamArr = urlParam.split('&')

  let dataStr = urlParamArr.find(item => item.includes('data'))
  const arr = JSON.parse(decodeURI(dataStr.split('=')[1]))

  let fpsUrlArr = urlParamArr.find(item => item.includes('fps'))
  const fps = fpsUrlArr ? JSON.parse(decodeURI(fpsUrlArr.split('=')[1])) : 20

  const StartEndObj = {}

  let state = true

  window.onload = async function () {
    if (!arr) return

    new DigitalTwinAPI()

    const idList = []
    for (let index in arr) idList.push(arr[index].id)
    const { data } = await fdapi.tileLayer.get(idList)
    const tickArr = []

    for (let index in arr) {
      const startLocation = data[index].location
      const endLocation = arr[index].location

      const line = getLineSegmentPoint([startLocation, endLocation], fps)
      StartEndObj[data[index].id] = line
    }
  }

  function clientCalled(str) {
    document.getElementById('r3').innerText = str
  }

  function tick(frame) {
    if (!arr) return
    if (!state) return

    fdapi.tileLayer.updateBegin()
    for (let key in StartEndObj) fdapi.tileLayer.setLocation(key, StartEndObj[key][i], null)
    fdapi.tileLayer.updateEnd()

    if (i >= fps - 1) {
      FdExternal.postEvent('tick end')
      i = 0
      state = false
      fdapi.removeTick()
    }
    i++
  }

  // 线段分点
  function getLineSegmentPoint(lineSegment, interval) {
    try {
      if (interval && lineSegment && lineSegment.length === 2) {
        const point1 = lineSegment[0]
        const point2 = lineSegment[1]

        const a = point2[1] - point1[1]
        const b = point2[0] - point1[0]
        const c = point2[2] - point1[2]

        const o = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2) + Math.pow(c, 2))

        const n = o / interval
        const p = []

        for (let i = 1; i <= interval; i++) {
          const x = (b / o) * (n * i) + point1[0]
          const y = (a / o) * (n * i) + point1[1]
          const z = (c / o) * (n * i) + point1[2]
          p.push([x, y, z])
        }
        return p
      } else {
        console.error('线段取点失败', lineSegment, interval)
      }
    } catch (error) {
      console.error('线段取点失败', error)
    }
  }

  function tick_next(o, frame) {}
</script>
